<template>
  <div class="control-section component-gap">
    <h3>🎮 方向与移动控制</h3>
    
    <!-- 控制参数配置 -->
    <div class="control-params">
      <div class="param-grid">
        <div class="param-item">
          <label>控制坐标系:</label>
          <select 
            v-model="currentControlMode" 
            class="param-select"
            @change="$emit('change-control-mode', currentControlMode)"
            :disabled="!isConnected || armed"
          >
            <option value="ENU">ENU坐标系（东-北-天）</option>
            <option value="BODY">机体坐标系（前-右-上）</option>
          </select>
          <p class="param-tip">⚠️ 坐标系切换仅在无人机锁定时生效</p>
        </div>

        <div class="param-item">
          <label>移动步长 (m):</label>
          <input 
            type="number" 
            v-model.number="currentStepSize" 
            class="param-input"
            min="0.1" 
            max="5" 
            step="0.1"
            @change="handleStepSizeChange"
            @blur="validateStepSize"
            :disabled="!isConnected"
          >
          <p class="param-tip">当前步长：{{ currentStepSize }} m</p>
        </div>

        <div class="param-item">
          <label>偏航角参考 (rad):</label>
          <input 
            type="number" 
            v-model.number="currentYawRef" 
            class="param-input"
            min="-3.14" 
            max="3.14" 
            step="0.1"
            @change="handleYawRefChange"
            @blur="validateYawRef"
            :disabled="!isConnected"
          >
          <p class="param-tip">当前偏航角：{{ (currentYawRef * 180/Math.PI).toFixed(1) }}°</p>
        </div>
      </div>
    </div>

    <!-- 方向控制盘 -->
    <div class="direction-pad-container">
      <h4>摇杆控制（需先解锁无人机）</h4>
      <div class="direction-pad">
        <!-- 摇杆控制区域 -->
        <div class="joystick-area">
          <div class="joystick-container">
            <div 
              class="joystick" 
              :class="{ disabled: !isConnected || !armed }"
              @mousedown="startJoystick"
              @touchstart="startJoystick"
              ref="joystick"
            >
              <div class="joystick-handle" :style="joystickPosition"></div>
            </div>
            <div class="joystick-center"></div>
          </div>
          
          <!-- 摇杆方向指示 -->
          <div class="direction-indicators">
            <div class="direction-indicator forward" :class="{ active: joystickDirection.forward }">
              <span>↑</span>
            </div>
            <div class="direction-indicator backward" :class="{ active: joystickDirection.backward }">
              <span>↓</span>
            </div>
            <div class="direction-indicator left" :class="{ active: joystickDirection.left }">
              <span>←</span>
            </div>
            <div class="direction-indicator right" :class="{ active: joystickDirection.right }">
              <span>→</span>
            </div>
          </div>
          
          <!-- 当前摇杆状态 -->
          <div class="joystick-status">
            <div class="status-item">
              <label>X:</label>
              <span>{{ joystickValues.x.toFixed(2) }}</span>
            </div>
            <div class="status-item">
              <label>Y:</label>
              <span>{{ joystickValues.y.toFixed(2) }}</span>
            </div>
            <div class="status-item">
              <label>强度:</label>
              <span>{{ joystickValues.intensity.toFixed(2) }}</span>
            </div>
          </div>
        </div>
        
        <!-- 垂直控制区域（上升/下降） -->
        <div class="vertical-controls">
          <div class="vertical-control-group">
            <button 
              @click="$emit('move-up')" 
              class="btn btn-altitude up" 
              :disabled="!isConnected || !armed"
            >
              <span class="direction-icon">⬆️</span>
              <span class="direction-text">上升</span>
            </button>
            
            <div class="altitude-display">
              <div class="altitude-bar">
                <div class="altitude-fill" :style="{ height: altitudePercentage + '%' }"></div>
              </div>
              <span class="altitude-value">{{ currentAltitude.toFixed(1) }}m</span>
            </div>
            
            <button 
              @click="$emit('move-down')" 
              class="btn btn-altitude down" 
              :disabled="!isConnected || !armed"
            >
              <span class="direction-icon">⬇️</span>
              <span class="direction-text">下降</span>
            </button>
          </div>
        </div>
      </div>
      
      <!-- 悬停按钮 -->
      <div class="hover-control">
        <button 
          @click="$emit('hover')" 
          class="btn btn-hover" 
          :disabled="!isConnected || !armed"
        >
          <span class="direction-icon">⏹️</span>
          <span class="direction-text">悬停</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'MovementControl',
  props: {
    isConnected: {
      type: Boolean,
      required: true,
      default: false
    },
    armed: {
      type: Boolean,
      required: true,
      default: false
    },
    controlMode: {
      type: String,
      required: true,
      default: 'ENU'
    },
    stepSize: {
      type: Number,
      required: true,
      default: 1.0
    },
    yawRef: {
      type: Number,
      required: true,
      default: 0
    },
    position: {
      type: Object,
      required: true,
      default: () => ({ x: 0, y: 0, z: 0 })
    }
  },
  data() {
    return {
      currentControlMode: this.controlMode,
      currentStepSize: this.stepSize,
      currentYawRef: this.yawRef,
      currentAltitude: 0,
      
      // 摇杆状态
      joystickActive: false,
      joystickValues: {
        x: 0,
        y: 0,
        intensity: 0
      },
      joystickDirection: {
        forward: false,
        backward: false,
        left: false,
        right: false
      }
    };
  },
  computed: {
    joystickPosition() {
      const maxOffset = 40; // 摇杆最大偏移量
      return {
        transform: `translate(${this.joystickValues.x * maxOffset}px, ${this.joystickValues.y * maxOffset}px)`
      };
    },
    altitudePercentage() {
      const maxAltitude = 10; // 假设最大高度10米
      return Math.min((this.currentAltitude / maxAltitude) * 100, 100);
    }
  },
  watch: {
    controlMode(newVal) {
      this.currentControlMode = newVal;
    },
    stepSize(newVal) {
      this.currentStepSize = newVal;
    },
    yawRef(newVal) {
      this.currentYawRef = newVal;
    },
    position: {
      handler(newVal) {
        this.currentAltitude = newVal.z;
      },
      deep: true
    },
    // 监听摇杆值变化，发送移动命令
    joystickValues: {
      handler(newVal) {
        if (this.joystickActive && newVal.intensity > 0.1) {
          this.sendJoystickCommand();
        }
      },
      deep: true
    }
  },
  mounted() {
    // 添加全局事件监听器
    document.addEventListener('mousemove', this.handleJoystickMove);
    document.addEventListener('mouseup', this.stopJoystick);
    document.addEventListener('touchmove', this.handleJoystickMove, { passive: false });
    document.addEventListener('touchend', this.stopJoystick);
  },
  beforeDestroy() {
    // 移除全局事件监听器
    document.removeEventListener('mousemove', this.handleJoystickMove);
    document.removeEventListener('mouseup', this.stopJoystick);
    document.removeEventListener('touchmove', this.handleJoystickMove);
    document.removeEventListener('touchend', this.stopJoystick);
  },
  methods: {
    handleStepSizeChange() {
      this.currentStepSize = this.validateStepSize();
      this.$emit('change-step-size', this.currentStepSize);
    },
    validateStepSize() {
      const min = 0.1;
      const max = 5;
      let val = this.currentStepSize;
      if (isNaN(val) || val < min) val = min;
      if (val > max) val = max;
      this.currentStepSize = Number(val.toFixed(1));
      return this.currentStepSize;
    },
    handleYawRefChange() {
      this.currentYawRef = this.validateYawRef();
      this.$emit('change-yaw-ref', this.currentYawRef);
    },
    validateYawRef() {
      const min = -Math.PI;
      const max = Math.PI;
      let val = this.currentYawRef;
      if (isNaN(val) || val < min) val = min;
      if (val > max) val = max;
      this.currentYawRef = Number(val.toFixed(2));
      return this.currentYawRef;
    },
    
    // 摇杆控制方法
    startJoystick(event) {
      if (!this.isConnected || !this.armed) return;
      
      event.preventDefault();
      this.joystickActive = true;
      this.handleJoystickMove(event);
    },
    
    handleJoystickMove(event) {
      if (!this.joystickActive) return;
      
      event.preventDefault();
      
      // 获取摇杆容器和触摸/鼠标位置
      const joystick = this.$refs.joystick;
      if (!joystick) return;
      
      const rect = joystick.getBoundingClientRect();
      const centerX = rect.left + rect.width / 2;
      const centerY = rect.top + rect.height / 2;
      
      let clientX, clientY;
      
      if (event.type.includes('touch')) {
        clientX = event.touches[0].clientX;
        clientY = event.touches[0].clientY;
      } else {
        clientX = event.clientX;
        clientY = event.clientY;
      }
      
      // 计算相对于中心的偏移量
      const deltaX = clientX - centerX;
      const deltaY = clientY - centerY;
      
      // 计算距离（移除了未使用的 angle 变量）
      const distance = Math.min(Math.sqrt(deltaX * deltaX + deltaY * deltaY), rect.width / 2);
      
      // 计算标准化值 (-1 到 1)
      const normalizedX = (deltaX / (rect.width / 2)) * (distance / (rect.width / 2));
      const normalizedY = (deltaY / (rect.height / 2)) * (distance / (rect.height / 2));
      const intensity = distance / (rect.width / 2);
      
      // 更新摇杆值
      this.joystickValues = {
        x: Math.max(-1, Math.min(1, normalizedX)),
        y: Math.max(-1, Math.min(1, normalizedY)),
        intensity: Math.max(0, Math.min(1, intensity))
      };
      
      // 更新方向指示器
      this.updateDirectionIndicators();
    },
    
    stopJoystick() {
      if (!this.joystickActive) return;
      
      this.joystickActive = false;
      
      // 重置摇杆位置
      this.joystickValues = {
        x: 0,
        y: 0,
        intensity: 0
      };
      
      // 重置方向指示器
      this.joystickDirection = {
        forward: false,
        backward: false,
        left: false,
        right: false
      };
      
      // 发送停止命令
      this.$emit('hover');
    },
    
    updateDirectionIndicators() {
      const { x, y, intensity } = this.joystickValues;
      const threshold = 0.3;
      
      this.joystickDirection = {
        forward: y < -threshold && intensity > threshold,
        backward: y > threshold && intensity > threshold,
        left: x < -threshold && intensity > threshold,
        right: x > threshold && intensity > threshold
      };
    },
    
    sendJoystickCommand() {
      // 根据摇杆方向发送对应的移动命令
      if (this.joystickDirection.forward && !this.joystickDirection.left && !this.joystickDirection.right) {
        this.$emit('move-forward');
      } else if (this.joystickDirection.backward && !this.joystickDirection.left && !this.joystickDirection.right) {
        this.$emit('move-backward');
      } else if (this.joystickDirection.left && !this.joystickDirection.forward && !this.joystickDirection.backward) {
        this.$emit('move-left');
      } else if (this.joystickDirection.right && !this.joystickDirection.forward && !this.joystickDirection.backward) {
        this.$emit('move-right');
      } else if (this.joystickDirection.forward && this.joystickDirection.left) {
        // 对角线移动 - 前进左
        this.$emit('move-forward');
        this.$emit('move-left');
      } else if (this.joystickDirection.forward && this.joystickDirection.right) {
        // 对角线移动 - 前进右
        this.$emit('move-forward');
        this.$emit('move-right');
      } else if (this.joystickDirection.backward && this.joystickDirection.left) {
        // 对角线移动 - 后退左
        this.$emit('move-backward');
        this.$emit('move-left');
      } else if (this.joystickDirection.backward && this.joystickDirection.right) {
        // 对角线移动 - 后退右
        this.$emit('move-backward');
        this.$emit('move-right');
      }
    }
  },
  emits: [
    'change-control-mode', 
    'change-step-size', 
    'change-yaw-ref',
    'move-forward',
    'move-backward', 
    'move-left',
    'move-right',
    'move-up',
    'move-down',
    'hover'
  ]
};
</script>

<style scoped>
.control-params {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.param-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 15px;
}

.param-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.param-item label {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
}

.param-select, .param-input {
  padding: 8px 12px;
  border: 2px solid #e0e0e0;
  border-radius: 4px;
  background: white;
  font-size: 14px;
  color: #2c3e50;
}

.param-input {
  width: 120px;
}

.param-tip {
  margin: 4px 0 0 0;
  color: #7f8c8d;
  font-size: 12px;
  line-height: 1.2;
}

.direction-pad-container {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.direction-pad-container h4 {
  margin: 0 0 15px 0;
  color: #2c3e50;
  font-size: 16px;
  text-align: center;
}

.direction-pad {
  display: flex;
  gap: 30px;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
}

/* 摇杆控制区域 */
.joystick-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.joystick-container {
  position: relative;
  width: 150px;
  height: 150px;
  background: #e9ecef;
  border-radius: 50%;
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.joystick {
  position: relative;
  width: 120px;
  height: 120px;
  background: #495057;
  border-radius: 50%;
  cursor: pointer;
  touch-action: none;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  transition: all 0.2s;
}

.joystick.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.joystick-handle {
  position: absolute;
  width: 40px;
  height: 40px;
  background: #3498db;
  border-radius: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transition: transform 0.1s;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.joystick-center {
  position: absolute;
  width: 10px;
  height: 10px;
  background: #e74c3c;
  border-radius: 50%;
  z-index: 1;
}

/* 方向指示器 */
.direction-indicators {
  display: grid;
  grid-template-areas: 
    ". forward ."
    "left . right"
    ". backward .";
  gap: 10px;
  margin-top: 10px;
}

.direction-indicator {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #dee2e6;
  border-radius: 4px;
  color: #6c757d;
  font-weight: bold;
  transition: all 0.2s;
}

.direction-indicator.active {
  background: #3498db;
  color: white;
  box-shadow: 0 0 8px rgba(52, 152, 219, 0.5);
}

.direction-indicator.forward { grid-area: forward; }
.direction-indicator.backward { grid-area: backward; }
.direction-indicator.left { grid-area: left; }
.direction-indicator.right { grid-area: right; }

/* 摇杆状态显示 */
.joystick-status {
  display: flex;
  gap: 15px;
  margin-top: 10px;
}

.status-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.status-item label {
  font-size: 12px;
  color: #6c757d;
  font-weight: 600;
}

.status-item span {
  font-size: 14px;
  color: #2c3e50;
  font-weight: bold;
}

/* 垂直控制区域 */
.vertical-controls {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.vertical-control-group {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.btn {
  padding: 12px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.btn-altitude {
  background: #9b59b6;
  color: white;
  min-width: 100px;
  min-height: 80px;
}

.btn-altitude.up {
  background: #2ecc71;
}

.btn-altitude.down {
  background: #e74c3c;
}

.direction-icon {
  font-size: 22px;
}

.direction-text {
  font-size: 12px;
}

/* 高度显示 */
.altitude-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.altitude-bar {
  width: 20px;
  height: 120px;
  background: #e9ecef;
  border-radius: 10px;
  overflow: hidden;
  position: relative;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
}

.altitude-fill {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  background: linear-gradient(to top, #2ecc71, #f39c12, #e74c3c);
  transition: height 0.5s ease;
}

.altitude-value {
  font-size: 12px;
  font-weight: bold;
  color: #2c3e50;
}

/* 悬停控制 */
.hover-control {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.btn-hover {
  background: #7f8c8d;
  color: white;
  min-width: 120px;
  min-height: 60px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .param-grid {
    grid-template-columns: 1fr;
  }
  
  .direction-pad {
    flex-direction: column;
    gap: 20px;
  }
  
  .joystick-container {
    width: 120px;
    height: 120px;
  }
  
  .joystick {
    width: 100px;
    height: 100px;
  }
  
  .joystick-handle {
    width: 35px;
    height: 35px;
  }
  
  .btn-altitude {
    min-width: 80px;
    min-height: 60px;
  }
  
  .altitude-bar {
    height: 100px;
  }
}
</style>